<?php

require_once 'db.php';
//number of characters for the entry. entry will be cut off at next 
define("perpost", 80);
define("perpage", 1);

class entry {
	public $id;  
	public $title;
	public $text;
	
	public function __construct($id, $title, $text) {
		$this->id = $id;
		$this->title = $title;
		$this->text = $text;
	}
}

class model {

	function connect() {
		try {
			$db = new PDO("mysql:host=".server.";dbname=".db,user,pass);
			return $db;
		} catch (Exception $e) {
			echo '</br><p>Error : ' . $e->getMessage() . '</p><br/>';
			die();
		}
	}
	function getpost($id)  {
		$db = $this->connect();
		$sql = $db->prepare("select * from entry where id=? limit 1");
		$sql->bindParam(1, $id, PDO::PARAM_INT);
		$sql->execute();
		if ($sql->rowCount() < 1) {
			$items = Array (
				1 => new entry(0, "Nothing Found", "Uh Oh! 404!")
			);
		} else {
			while ($row = $sql->fetch()) {
				$items = Array (
					$row[0] => new entry($row[0],$row[1],$row[2]),
				);
			}
		}
		return $items;
	}
	function getallposts($page) {
		$start = ($page-1)*perpage;
		$db = $this->connect();
		if (perpage == 0) {
			$sql = $db->prepare("select * from entry ");
		} else {
			$sql = $db->prepare("select * from entry order by time limit $start," . perpage);
		}
		$sql->execute();
		if ($sql->rowCount() < 1) {
			$items = Array (
				1 => new entry(0, "Nothing Found", "Uh Oh! 404!")
			);
		} else {
			$items = Array();
			while ($row = $sql->fetch()) {
				$row['entry'] = $this->trim_post($row['entry'],perpost);
				$items[$row['id']] = new entry($row['id'],$row['title'],$row['entry']);
			}
		}
		return $items;
	}
	
	function pages() {
		$db = $this->connect();
		$sql = $db->prepare("select * from entry");
		$sql->execute();
		if (perpage > 0) {
			return ceil($sql->rowCount()/perpage);
		}
	}
	
	//temporary function to limit number of words
	//takes the string and the number of characters (not words) and cuts off at next space
	function trim_post($str,$num) {
		if (strlen($str) > $num) {
			$str = wordwrap($str, $num);
			$str = substr($str, 0, strpos($str, "\n"));
		}
		return $str;
	}
}

?>